#include "ConvertNativeImageToGrey.h"

#include <QErrorMessage>
#include <QMessageBox>
#include <QString>

#include "itkImageRegionConstIterator.h"
#include "itkNumericTraits.h"
#include "itkCastImageFilter.h"

#include "itkImageToVTKImageFilter.h"
#include "vtkImageActor.h"
#include "vtkRenderWindow.h"
#include "vtkRenderWindowInteractor.h"
#include "vtkInteractorStyleImage.h"
#include "vtkSmartPointer.h"
#include "vtkRenderer.h"

GreyImageType*
ConvertNativeImageToGrey::operator()(InputImagePointer nativeImage,
                                     itk::ImageIOBase::IOComponentType pixelType)
{
    switch(pixelType)
    {
    case itk::ImageIOBase::UCHAR:  DoCast<unsigned char>(nativeImage);        break;
    case itk::ImageIOBase::CHAR:   DoCast<signed char>(nativeImage);          break;
    case itk::ImageIOBase::USHORT: DoCast<unsigned short>(nativeImage);       break;
    case itk::ImageIOBase::SHORT:  DoCast<signed short>(nativeImage);         break;
    case itk::ImageIOBase::UINT:   DoCast<unsigned int>(nativeImage);         break;
    case itk::ImageIOBase::INT:    DoCast<signed int>(nativeImage);           break;
    case itk::ImageIOBase::ULONG:  DoCast<unsigned long>(nativeImage);        break;
    case itk::ImageIOBase::LONG:   DoCast<signed long>(nativeImage);          break;
    case itk::ImageIOBase::FLOAT:  DoCast<float>(nativeImage);                break;
    case itk::ImageIOBase::DOUBLE: DoCast<double>(nativeImage);               break;
    default:
        (new QErrorMessage())->showMessage("Unknown Pixel Type when reading image");
      }
    return m_OutputImage.GetPointer();
}

template<typename TNative>
void
ConvertNativeImageToGrey::DoCast(InputImagePointer nativeImage)
{
    typedef itk::Image<TNative,3> NativeImageType;
    typedef typename NativeImageType::Pointer NativeImagePointer;
    typedef itk::CastImageFilter<NativeImageType, GreyImageType> CastImageFilterType;
    typename CastImageFilterType::Pointer castFilter = CastImageFilterType::New();

    NativeImagePointer image = dynamic_cast<NativeImageType *>(nativeImage.GetPointer());

    castFilter->SetInput(image);
    m_OutputImage = castFilter->GetOutput();
    castFilter->Update();
}



